const express = require('express');
const request = require('superagent');
const timeout = require('connect-timeout');
const app = express();
var bodyParser = require('body-parser');


//这里从环境变量读取配置，方便命令行启动
const { HOST = 'http://121.201.14.250:84', PORT = '3300' } = process.env;
//超时时间
const TIME_OUT = 30 * 1e3;
//设置端口
app.set('port', 7810);
//转换 body 用于转发时读取
app.use(bodyParser.json()); //加载解析json的中间件
app.use(bodyParser.urlencoded({
    extended: false
})); //加载解析urlencoded请求体的中间件

//设置超时 返回超时响应
app.use(timeout(TIME_OUT));
app.use((req, res, next) => {
    if (!req.timedout) next();
});

app.all('/**', function (req, res, next) {
	res.header('Access-Control-Allow-Credentials', 'true');
	res.header("Access-Control-Allow-Origin", "*");
	res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
	res.header("Access-Control-Allow-Headers", "X-Requested-With,cache-control,content-type,hash-referer");
	next();
});

//反向代理（这里把需要进行反代的路径配置到这里即可）
//eg:将/api/test 代理到 ${HOST}/api/test
app.use('/**', function (req, res) {
    //获得方法类型
    const method = req.method.toLowerCase();
    const sreq = request[method](HOST + req.originalUrl);
    console.log(method, HOST + req.originalUrl)
    //如果为 post 或者 put 则需要发送时传递body
    if (method === 'post' || method === 'put') {
        sreq.set('Content-Type', 'application/json')
            .send(req.body)
    }
    sreq.pipe(res);
    sreq.on('end', function (error, result) {
        if (error) {
            console.log(error);
            return;
        }
    });
});

//静态页面
//这里一般设置你的静态资源路径
// app.use('/route', express.static('src'));

//监听端口
app.listen(app.get('port'), () => {
    console.log(`server running @${app.get('port')}`)
});